package com.baidu.bulls.stock.user.config;

import com.baidu.bulls.stock.common.exception.BusinessException;
import com.baidu.bulls.stock.common.exception.ComponentException;
import com.baidu.bulls.stock.common.exception.constants.IErrorCodeEnum;
import com.baidu.bulls.stock.entity.user.TradeUser;
import com.baidu.stock.common.web.vo.ApiRespResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * 参数异常校验统一处理
 */
@ControllerAdvice
@Slf4j
public class ParamValidExceptionHandle {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public @ResponseBody ApiRespResult handle(MethodArgumentNotValidException ex){
        log.warn("enter BingExceptionHandle");
        StringBuffer buffer = new StringBuffer();
        //获得错误的字段，以及错误原因
        List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            //拼接错误信息
            buffer.append(fieldError.getField()).append(":").append(fieldError.getDefaultMessage()).append("\t");
        }
        ApiRespResult result = ApiRespResult.validError(buffer.toString());
        return result;
    }

    @ExceptionHandler(ComponentException.class)
    public @ResponseBody ApiRespResult CompoHandle(ComponentException ex){
        log.error(ex.getMessage(),ex);
        ApiRespResult<TradeUser> result = ApiRespResult.error(ex.geterrorCodeEnum());
        return result;
    }

    @ExceptionHandler(BusinessException.class)
    public @ResponseBody ApiRespResult CompoHandle(BusinessException ex){
        log.error(ex.getMessage(),ex);
        ApiRespResult<TradeUser> result = ApiRespResult.error(ex.geterrorCodeEnum());
        return result;
    }

}
